using System.Text;
using Engine.Input;
using Game;
using GameEntitySystem;
using SCIENEW.Tech;
using TemplatesDatabase;

namespace SCIENEW {
    public class SubsystemTechTree : Subsystem, IUpdateable {
        public UpdateOrder UpdateOrder => UpdateOrder.Default;
        public TechTree TechTree;

        public override void Load(ValuesDictionary valuesDictionary) {
            base.Load(valuesDictionary);
            TechTree = TechTreeManager.TechTree;
            string data = valuesDictionary.GetValue("UnlockedNodes", string.Empty);
            if (!string.IsNullOrEmpty(data)) {
                string[] unlockedNodes = data.Split(';', StringSplitOptions.RemoveEmptyEntries);
                TechTree.UnlockNodes(unlockedNodes);
            }
        }

        public override void Save(ValuesDictionary valuesDictionary) {
            base.Save(valuesDictionary);
            StringBuilder stringBuilder = new();
            TechNode[] unlockedNode = TechTree.GetUnlockedNodes();
            foreach (var uNode in unlockedNode) {
                stringBuilder.Append(uNode.Name);
                stringBuilder.Append(';');
            }
            if (stringBuilder.Length > 0) stringBuilder.Remove(stringBuilder.Length - 1, 1);
            valuesDictionary.SetValue("UnlockedNodes", stringBuilder.ToString());
        }

        public override void Dispose() {
            base.Dispose();
            TechTreeManager.ResumeToDefault();//将科技树恢复至默认状态
        }

        public void Update(float dt) {
            if (Keyboard.IsKeyDownOnce(Key.Z)) {
                Show();
            }
            else if (Keyboard.IsKeyDownOnce(Key.X)) {
                ScreensManager.SwitchScreen("Recipaedia");
            }
        }

        public void Show() {
            ScreensManager.SwitchScreen("TechTree", TechTree);
        }

        public void Unlock(int blockValue, ComponentPlayer player) {
            bool unlockState = TechTree.UnlockNode(blockValue, out TechNode unlockedNode);
            if (!unlockState && unlockedNode != null) player.ComponentGui.DisplayLargeMessage("解锁科技树节点", unlockedNode.DisplayName, 3f, 0);
        }
    }
}